﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SyncApplication.Business
{

    public class AuthenticationHandle
    {
        public static string Encode(string userName, string password, string token)
        {
            string sbase = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + "-::-" + password + "-::-" + token));
            List<byte> lstConten = new List<byte>(Encoding.ASCII.GetBytes(sbase));

            Random r = new Random();
            List<byte> lstHole = new List<byte>();

            int max = lstConten.Count;
            if (max > 255)
                max = 254;
            int maxCount = 10;
            if (lstConten.Count < 10)
                maxCount = lstConten.Count - 1;
            while (lstHole.Count < maxCount)
            {
                int t = r.Next(0, lstConten.Count);
                if (!lstHole.Contains((byte)t))
                {
                    lstHole.Add((byte)t);
                    lstConten.Insert(t, (byte)t);
                }
            }
            List<byte> temp = new List<byte>();
            temp.AddRange(lstHole);
            temp.AddRange(Encoding.ASCII.GetBytes("-::-"));
            temp.AddRange(lstConten);
            return Convert.ToBase64String(temp.ToArray());

        }
        public static string[] Decode(string encode)
        {
            Byte[] temp1 = Convert.FromBase64String(encode);           
            string s = Encoding.ASCII.GetString(temp1);
            string[] part = s.Split(new string[]{"-::-"},2, StringSplitOptions.None);
            string strHole = part[0];
            byte[] hole = Encoding.ASCII.GetBytes(strHole);

            List<Byte> lstData = new List<byte>();
            //byte[] temp2 = new byte[temp1.Length - hole.Length];
            //temp1.CopyTo(temp2, hole.Length);
            lstData.AddRange(Encoding.ASCII.GetBytes(part[1]));
            for (int i = hole.Length - 1; i >= 0; i--)
            {
                lstData.RemoveAt(hole[i]);
            }
            string s1= Encoding.ASCII.GetString(lstData.ToArray());
            string s2 = Encoding.ASCII.GetString(Convert.FromBase64String(s1));
            return s2.Split(new string[]{"-::-"}, StringSplitOptions.RemoveEmptyEntries);

        }

    }
}
